<?php

iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "UTF-8");
require('CryptAES.php');

class HttpClient {

	private $options;

	private $config;

	private $reqData;

	function __construct($config)
	{
		$this->config = $config;
	}

	public function setReqData($reqData)
	{
		$this->reqData = $reqData;
	}

	public function getReqData()
	{
		return $this->reqData;
	}

	public function getConfig()
	{
		if(!isset($this->config)) {
			$this->config = require('Config.php');
		}
		return $this->config;
	}

	public function setOptions() 
	{
		$reqData = $this->getReqData();
		list($t1, $t2) = explode(' ', microtime());
		$time =  (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
		$config = $this->getConfig();
		$header = array(
			'Content-Type: application/json; charset=utf-8',
			'Content-Length: ' . strlen($reqData),
			'key:' . $config['key'],
			'validate-token:' . $this->myMd5($config['key'], $config['token'], $time),
			'timestamp:' . $time,	
			);
		$options = array(
        	CURLOPT_HEADER => true,
        	CURLOPT_HTTPHEADER => $header,
        	CURLOPT_POSTFIELDS => $reqData,
        	CURLOPT_POST => true,
			);
		$this->options = $options;
 	}

	public function getOptions()
	{
		if(!isset($this->options)){
			$this->setOptions();
		}
		return $this->options;
	}

	
	
	
	

	public function post($url, $reqData) 
	{
		$config = $this->getConfig();
		$url = $config['host'].$url;
		// $url = $config['host'];
		//echo 'data:' . $reqData . '</br>';

		$aes = new CryptAES();
		$reqData = $aes->encrypt($reqData, $this->config['token']);
		// $reqData = 'ssssss';
		$this->setReqData($reqData);
		//echo 'aes-data:: ' . $this->reqData . '</br>';

		$ch = curl_init($url);
		curl_setopt_array($ch, $this->getOptions());
		ob_start();
		curl_exec($ch);
		$resData = ob_get_contents();
		

		ob_end_clean();
		curl_close($ch);
		//echo 'resData:'  . '</br>';
        //var_dump($resData);		
		$resData= explode("{", $resData);
		array_shift($resData);		
	    $resData = implode("{", $resData);		
	    $resData = '{' . $resData;		

		echo 'resData:'  . '</br>';
        var_dump($resData);
		return $resData;
	}

	public function myMd5($key, $token, $time){
		return md5($key . $token . $time);
	}
}
?>